//
//  MainViewController.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/8/31.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()        
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        setupComposedButton()
    }
    
     // MARK: - 事件的监听
    @objc private func composeButtonClicked()
    {
        let com = ComposeViewController()
        let nav = UINavigationController(rootViewController: com)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    // MARK: - 添加子控制器
    // 添加子控制器
    private func addChildViewControllers()
    {
        // 设置渲染颜色
        // self.tabBar.tintColor = UIColor.orangeColor()
        addChildViewController(HomeTableViewController(),title: "首页",imageNamed: "tabbar_home")
        addChildViewController(DiscoveryTableViewController(),title: "发现",imageNamed: "tabbar_discover")
        addChildViewController(UIViewController())
        addChildViewController(MessageTableViewController(),title: "消息",imageNamed: "tabbar_message_center")
        addChildViewController(ProfileTableViewController(),title: "我",imageNamed: "tabbar_profile")
    }
    
    private func addChildViewController(vc:UIViewController ,title:String, imageNamed:String) {
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageNamed)
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
    // MARK: - 懒加载控件
    // 撰写按钮
    lazy var composedButton : UIButton = {
        
        let button = UIButton()
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "composeButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        self.tabBar.addSubview(button)
        
        
        return button
        }()
    
    // MARK: - 设置撰写按钮的frame
    private func setupComposedButton() {
        
        let count = childViewControllers.count
        
        let w = self.tabBar.bounds.width / CGFloat(count)
        
        let rect = CGRect(x: 0, y: 0, width: w, height: self.tabBar.bounds.height)
        
        composedButton.frame = CGRectOffset(rect, 2 * w , 0)
        
    }
    
}
